import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Users from '../page/user/Users.vue'
import Rights from '../page/power/Rights.vue'
import Roles from '../page/power/Roles.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    meta: {
      title: '首页'
    },
    children: [
      { path: '/users', component: Users, meta: { title: '用户信息表' } },
      { path: '/rights', component: Rights, meta: { title: '用户权限管理' } },
      { path: '/roles', component: Roles, meta: { title: '用户角色列表' } }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 导航守卫
router.beforeEach((to, from, next) => {
  // 设置页面title
  if (to.meta.title) {
    document.title = to.meta.title
  }

  if (to.path === '/login') {
    return next()
  }

  // 获取用户token
  const token = window.sessionStorage.getItem('token')
  if (!token) {
    return next('/login')
  }
  next()
})

export default router
